import React, {useEffect, useRef} from "react";
import TopBox from "./topBox/TopBox";
import style from './desktop.module.less'
import peer from "../../../components/peer";
export function Desktop(){


    const videoRef = useRef(null);

    useEffect(() => {
        videoRef.current = document.getElementById('video');
        return () => {
            videoRef.current = null;
        };
    }, []);

    const handleStream = (stream) => {
        if (videoRef.current) {
            videoRef.current.srcObject = stream;
            videoRef.current.onloadedmetadata = () => [
                videoRef.current.play(),
            ]
        }
    };

    const getStream = async (screenId) => {
        try {
            const stream = await navigator.mediaDevices.getUserMedia({
                audio: false,
                video: {
                    mandatory: {
                        chromeMediaSource: 'desktop',
                        chromeMediaSourceId: screenId
                    }
                }
            });
            handleStream(stream);
        } catch (e) {
            console.error('Error getting stream:', e);
        }
    };

    const changeScreens = (screenId) => {
        console.log(screenId);
        getStream(screenId);
    };

    useEffect(() => {
        peer.on('add-stream', (stream) => {
            handleStream(stream);
        });

        // 清理函数
        return () => {
            peer.off('add-stream', (stream) => {
                handleStream(stream);
            });
        };
    }, []);

    return (
        <div>
            <div className={style.container}>
                <TopBox onCallback={changeScreens}/>
                <video id={'video'} ref={videoRef}  autoPlay  muted className={style.video}></video>
            </div>
        </div>
    )
}